var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var loginRouter = require('./routes/loginRouter');
var registerRouter = require('./routes/registerRouter');
var usersRouter = require('./routes/users');

var app = express();

// app.listen(3000,function () {
//   console.log("我跑在3000上");
// })

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/login', loginRouter);
app.use('/register', registerRouter);
app.use('/users', usersRouter);



/*
    4.5监听用户点击登录操作
    method:
        post
*/
// app.post("/dologin", function (req, res) {
//   res.send("登录成功");
// });
// 以下只是模拟获取数据的测试效果正常提交数据还是post请求
app.get("/dologin", function (req, res) {
  let params = req.query;
  console.log("参数是：", params); // { username: '李四', password: '123456' }
  res.send("登录成功");
});

/*
    4.6监听用户注册提交数据
    method:
        post
*/
app.post("/doregister", function (req, res) {
  // 获取用户表单post提交的数据
  let params = req.body;
  console.log("params:", params);
  res.send("post提交注册成功！");
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// 4.使用express提供的路由方法（get|post|delete|put）处理客户端用户的个各种请求
/*
    4.1设置本服务的基础请求接口
    method:
        get
*/

app.get('/', function (req,res) {
  console.log("用户请求了根路径");
  res.send("hello node")
});
/*
    4.2返回用户信息接口
    method:
        get
*/
app.get('/userlist', function (req,res) {
  console.log("用户请求了根路径下的userlist");
  // 组装响应的数据
  let result = {
    code: 200,
    msg: "请求成功",
    data: [
      { id: 11, name: "鲁班" },
      { id: 2, name: "李白" },
    ],
  };
  res.send(result)
});




// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
